=begin

This file is part of the RSIF project, http://rsif.googlecode.com

Copyright (c) 2009-2009 Roberto Dario Seminara <robertodarioseminara@gmail.com>

rsif is free software: you can redistribute it and/or modify
it under the terms of the gnu general public license as published by
the free software foundation, either version 3 of the license, or
(at your option) any later version.

rsif is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.  see the
gnu general public license for more details.

you should have received a copy of the gnu general public license
along with rsif.  if not, see <http://www.gnu.org/licenses/>.
=end

require "singleton"

module Rsif
module Core
module Localization

class LocaleModule

	include Rsif::Core::Logging

	attr_accessor	:language

	def initialize
		@hash = Hash.new
	end
	def add_path( path )
		File.open( path ) do |file|

			begin

				rubycode = 
<<EOS
				#{file.read}
				local_variables.each do |vn|
					self.add_value(vn, eval(vn))
				end
EOS
				eval rubycode

			rescue Exception => e

				# es dificil resolver si se puede internacionalizar este texto
				# ya q se usa justamente en esta seccion que resuelve los 
				# asuntos de cargar esos strings
				logger.error "cannot load locale module #{path}: #{e}"

			end
		end
	end
	
	def add_value( macroname, value )
	    @hash[ macroname ] = value
	end

	def evaluate(macro) 
		@hash[macro]
	end
	
	def value( macro, *args)
		format = evaluate(macro) || "undefined symbol #{macro} args: #{ args.join(", ") } "
		format % args #
	end
end

class MultipleLocaleModule

	attr_accessor	:main_language
	attr_reader	:modules

	def initialize
		@modules = Array.new
	end

	def add_mod( modl)

		@modules << modl
		update_orders
	end

	def update_orders
		@modules.sort!{ |x,y| weight(y) <=> weight(x) }
	end

	def weight(modl)
		modl.language == self.main_language ? 10:0
	end

	def evaluate(macro)
		@modules.each do |modl|
			val = modl.evaluate(macro)
			return val if val
		end

		nil
	end
	
end

class Manager
	include Singleton

	include Rsif::Core::Logging

	attr_accessor	:main_module
	attr_accessor	:language

	# cambia el lenguaje
	def self.language=(l)
		self.instance.language = l
	end

	def language=(l)
		@language = l
		@main_module.main_language = l
	end
		
	
	def initialize
		@main_module = MultipleLocaleModule.new
	end

	# evalua el valor de una macro, tiene en cuenta el lenguaje especificado
	def evaluate( macro )
		main_module.evaluate(macro)
	end

	# carga un archivo de locale dado el path
	def add_locale_module( path )
		l = load_module(path)
		@main_module.add_mod(l)
	end

private
	def load_module( path )
		modl = LocaleModule.new
		modl.language = path.split(/\./)[-2]
		modl.add_path( path )

		logger.debug "loading Locale module from file #{path}, language \"#{modl.language}\""

		modl
	end

	
	
end

end
end
end

